package com.netintech.intelligenceInterface.iflytek.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lining
 * @date 2021/4/30 11:12
 * 用户使用 鉴权
 */
public class UserAuthUtils {

    public static final String ALGORITHM_NAME = "hmacsha256";

    public static Map<String, String> assembleRequestHeader(String httpMethod, String requestUrl, String apiKey, String apiSecret) {
        URL url;
        try {
            url = new URL(requestUrl);
            // 获取日期 如果时间相差5分钟，请求将会被拒绝
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = format.format(new Date());
            // 计算body 摘要(SHA256)
            String host = url.getHost();
            //使用hmac-sha256计算签名
            Mac mac = Mac.getInstance(ALGORITHM_NAME);
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), ALGORITHM_NAME);
            mac.init(spec);
            //构建签名计算所需参数
            String builder = "host: " + host + "\n" +
                    "date: " + date + "\n" +
                    httpMethod + " " + url.getPath() + " HTTP/1.1";
            byte[] hexDigits = mac.doFinal(builder.getBytes(StandardCharsets.UTF_8));
            String sha = Base64.getEncoder().encodeToString(hexDigits);
            // 构建header
            String headers = "host date request-line";
            String authorization = String.format("hmac api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", headers, sha);
            Map<String, String> header = new HashMap<>();
            header.put("authorization", authorization);
            header.put("host", host);
            header.put("date", date);
            return header;
        } catch (Exception e) {
            throw new RuntimeException("assemble requestHeader  error:" + e.getMessage());
        }
    }
}
